﻿using System;
using System.Collections.Generic;
using Common.Devices.Comm.Model.Helper;
using Helper;

namespace Common.Devices.Comm.Model
{
    /// <summary>
    /// Tcp客户端 连接参数  
    /// </summary>
    public class TcpClientInfo : CommParameter
    {
        public TcpClientInfo()
        {
            Ip = "127.0.0.1";
            Port = 8000;
            TimeOut = 60;
        }

        public TcpClientInfo(Uri uri)
        {
            SetParameter(uri);
        }

        public sealed override void SetParameter(Uri uri)
        {
            Ip = uri.Host;
            Port = uri.Port;
            TimeOut = int.Parse(uri.GetQueryParameter("TimeOut"));
        }
        [Property(PropertyType.String, "IP地址", "127.0.0.1")]
        public string Ip { get; set; }
        [Property(PropertyType.Number, "端口", "80")]
        public int Port { get; set; }

        [Property(PropertyType.Number, "超时时间", "60")]
        public int TimeOut { get; set; }

        public override Uri ToUri()
        {
            //var uriBuilder = new UriBuilder("tcp://172.0.1.1:9999?baud=999&Stop=1&Odd=None");
            try
            {
                return new UriBuilder("tcp://" + Ip + ":" + Port + "?" + "TimeOut=" + TimeOut).Uri;
            }
            catch (Exception)
            {
                return new UriBuilder("tcp://" + Ip + "?" + "TimeOut=" + TimeOut).Uri;

            }
        }

        public override string ToUriString()
        {
            return ToUri().ToString();
        }

        public override bool SetParameter(List<PropertyAttribute> parameter)
        {
            try
            {
                if (!string.IsNullOrEmpty(GetValue(parameter, "Ip")))
                {
                    Ip = GetValue(parameter, "Ip");
                }
                if (!string.IsNullOrEmpty(GetValue(parameter, "Port")))
                {
                    Port = Convert.ToInt32(GetValue(parameter, "Port"));
                }
                if (!string.IsNullOrEmpty(GetValue(parameter, "TimeOut")))
                {
                    TimeOut = Convert.ToInt32(GetValue(parameter, "TimeOut"));
                }
                return true;
            }
            catch (Exception)
            {
                // ignored
            }

            return false;
        }
    }



}
